package q391_isRectangleCover;

public class Solution_1 {
    /*
    完美矩形
    该解法是结合了数学的方式 —— 格林公式
    如果所有的小矩形围成了一个大矩形，那么对任意二维可微函数P,Q，
    在大矩形的边缘进行的线积分和所有小矩形上的面积分之间存在格林公式
     */
    public boolean isRectangleCover(int[][] rectangles) {
        int mx1 = rectangles[0][0], my1 = rectangles[0][1];
        int mx2 = rectangles[0][2], my2 = rectangles[0][3];
        int S = 0, s1 = 0, s2 = 0, s3 = 0;
        for (int[] rectangle : rectangles) {
            mx1 = Math.min(mx1, rectangle[0]);
            my1 = Math.min(my1, rectangle[1]);
            mx2 = Math.max(mx2, rectangle[2]);
            my2 = Math.max(my2, rectangle[3]);
            int x1 = rectangle[2] - rectangle[0], x2 = rectangle[2] * rectangle[2] - rectangle[0] * rectangle[0];
            int y1 = rectangle[3] - rectangle[1], y2 = rectangle[3] * rectangle[3] - rectangle[1] * rectangle[1];
            S += x1 * y1;
            s1 += x2 * y1;
            s2 += x1 * y2;
            s3 += x2 * y2;
        }
        return S == (mx2 - mx1) * (my2 - my1) && s1 == (mx2 * mx2 - mx1 * mx1) * (my2 - my1) && s2 == (mx2 - mx1) * (my2 * my2 - my1 * my1) && s3 == (mx2 * mx2 - mx1 * mx1) * (my2 * my2 - my1 * my1);

    }
}
